package com.dataporter.gather.web;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dataporter.gather.server.GatherServer;
import com.dataporter.gather.server.TemperatureService;

/**
 * 初始化并起动采集服务程序
 * 
 * @author ggeagle
 *
 */
@SuppressWarnings("serial")
public class GatherServerServlet extends HttpServlet {
	/**
	 * 日志记录器
	 */
	private Logger logger = LoggerFactory.getLogger(GatherServer.class);
	/**
	 * 采集服务
	 */
	private GatherServer gatherServer;
	/**
	 * 服务的端口号
	 */
	private int port = 10000;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String portValue = config.getInitParameter("serverPort");
		if (StringUtils.isNotBlank(portValue)) {
			port = Integer.parseInt(portValue);
		}
		WebApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(config.getServletContext());
		TemperatureService temperatureService = (TemperatureService) context
				.getBean("temperatureService");
		try {
			this.gatherServer = new GatherServer(port);
			this.gatherServer.setTemperatureService(temperatureService);
			new Thread(this.gatherServer).start();
		} catch (IOException e) {
			logger.error("起动采集任务失败：", e);
		}
	}

	@Override
	public void destroy() {
		super.destroy();
		this.gatherServer = null;
	}
}